/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */ // server.setExecutor(Executors.newFixedThreadPool(15));
package gamecontrollerserver;

import java.awt.AWTException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.concurrent.Executors;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import java.awt.Dimension;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

//


/**
 *
 * @author Luka Hale
 */
public class ServerHandler implements HttpHandler {

    private HttpServer server;
    private int port;
    public ServerHandler(int port) {
        try {
            this.port = port;
            robot = new Robot();
            Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
            screenX = (int) dim.getWidth();
            screenY = (int) dim.getHeight();
        } catch (AWTException ex) {
            Logger.getLogger(ServerHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void startServer() {


        try {
            InetSocketAddress addr = new InetSocketAddress(port);
            server = HttpServer.create(addr, 0);
            server.createContext("/", this);
            server.setExecutor(Executors.newCachedThreadPool());
            server.start();
            System.out.println("Server started...");
        } catch (IOException ex) {
            Logger.getLogger(ServerHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
   }

    public void stopServer() {
        server.stop(2);

        System.out.println("Server stopped...");
    }
    private Robot robot;
    PointerInfo info = MouseInfo.getPointerInfo();
    Point location = info.getLocation();
    private int orgX = location.x;
    private int orgY = location.y;
    private int screenX, screenY;
    private int firstX, firstY;
    int difX, difY;

    public void handle(HttpExchange exchange) throws IOException {
        String requestMethod = exchange.getRequestMethod();
        exchange.getResponseBody().write("LOOOl".getBytes());
        
        if (requestMethod.equalsIgnoreCase("POST")) {
            Headers responseHeaders = exchange.getResponseHeaders();
            responseHeaders.set("Content-Type", "text/plain");
            exchange.sendResponseHeaders(200, 0);
            Headers requestHeaders = exchange.getRequestHeaders();

            if (requestHeaders.containsKey("KeyPressed")) {
                List<String> key = requestHeaders.get("key");
                System.out.println("key pressed: " + key.get(0));
                String keyPressed = key.get(0);

                if (keyPressed.equals("up")) {
                    try {
                        robot.keyPress(KeyEvent.VK_W);
                        Thread.sleep(5000);
                        robot.keyRelease(KeyEvent.VK_W);
                        //                    robot.keyRelease(KeyEvent.VK_UP);
                        //                    robot.keyRelease(KeyEvent.VK_UP);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(ServerHandler.class.getName()).log(Level.SEVERE, null, ex);
                    }
                } else if (keyPressed.equals("down")) {
                    robot.keyPress(KeyEvent.VK_S);
                    robot.keyRelease(KeyEvent.VK_S);
//                    robot.keyPress(KeyEvent.VK_DOWN);
//                    robot.keyRelease(KeyEvent.VK_DOWN);
                } else if (keyPressed.equals("left")) {
                    robot.keyPress(KeyEvent.VK_A);
                    robot.keyRelease(KeyEvent.VK_A);
//                    robot.keyPress(KeyEvent.VK_LEFT);
//                    robot.keyRelease(KeyEvent.VK_LEFT);
                } else if (keyPressed.equals("right")) {
                    robot.keyPress(KeyEvent.VK_D);
                    robot.keyRelease(KeyEvent.VK_D);
//                    robot.keyPress(KeyEvent.VK_RIGHT);
//                    robot.keyRelease(KeyEvent.VK_RIGHT);
                }


            } else if (requestHeaders.containsKey("touchBegan")) {
                difX = 0;
                difY = 0;
                List<String> xList = requestHeaders.get("X");
                List<String> yList = requestHeaders.get("Y");
                firstX = (int) Double.parseDouble(xList.get(0));
                firstY = (int) Double.parseDouble(yList.get(0));
            } else if (requestHeaders.containsKey("touchMovement")) {

                List<String> xList = requestHeaders.get("X");
                List<String> yList = requestHeaders.get("Y");

                int moveX = (int) Double.parseDouble(xList.get(0));
                int moveY = (int) Double.parseDouble(yList.get(0));

                info = MouseInfo.getPointerInfo();
                location = info.getLocation();
                //System.out.println("---> location x:"+location.x + " y:"+ location.y);

                int newX = 0;
                int newY = 0;
                if (firstX < moveX) {
                    difX = difX + moveX - firstX;
                    newX = location.x + (difX / 280);
                    if (newX > screenX) {
                        newX = screenX;
                    }

                } else {
                    difX = difX + firstX - moveX;
                    newX = location.x - (difX / 280);
                    if (newX < 0) {
                        newX = 0;
                    }

                }
                if (firstY < moveY) {
                    difY = difY + moveY - firstY;
                    newY = location.y + (difY / 280);
                    if (newY > screenY) {
                        newY = screenY;
                    }
                } else {
                    difY = difY + firstY - moveY;
                    newY = location.y - (difY / 280);
                    if (newY < 0) {
                        newY = 0;
                    }
                }
                System.out.println("Move to X:" + newX + " y: " + newY);
                robot.mouseMove(newX, newY);

            } else if (requestHeaders.containsKey("touchEnded")) {
            } else if (requestHeaders.containsKey("leftClick")) {
                System.out.println("leftClick");
                robot.mousePress(InputEvent.BUTTON1_MASK);
                robot.mouseRelease(InputEvent.BUTTON1_MASK);
            } else if (requestHeaders.containsKey("rightClick")) {

                System.out.println("rightClick");
                robot.mousePress(InputEvent.BUTTON3_MASK);
                robot.mouseRelease(InputEvent.BUTTON3_MASK);

            } else {
                //X
                List<String> xList = requestHeaders.get("X");
                double x = Double.parseDouble(xList.get(0)) * 40;
                System.out.println("X:" + x);



//                //Y
//                List<String> yList = requestHeaders.get("Y");
//                double y = Double.parseDouble(yList.get(0)) * 25;
//                System.out.println("Y:" + y);

                //Z
                List<String> yList = requestHeaders.get("Z");
                double y = Double.parseDouble(yList.get(0)) * 40;
                System.out.println("Y:" + y);


                System.out.println("x=" + location.x + " y=" + location.y);
                orgX = orgX + (int) x;
                orgY = orgY + (int) y;

                if (orgX > screenX) {
                    orgX = screenX;
                }
                if (orgX < 0) {
                    orgX = 0;
                }

                if (orgY > screenY) {
                    orgY = screenY;
                }
                if (orgY < 0) {
                    orgY = 0;
                }
                setNewCoords(orgX, orgY);
            }




        }
    }

    public void setNewCoords(int x, int y) {
        robot.mouseMove(x, y);
    }
}
